<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>17.1. threading — Thread-based parallelism &mdash; Python 3.4.3 documentation</title>
    
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.4.3',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.4.3 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python 3.4.3 documentation" href="../index.html" />
    <link rel="up" title="17. Concurrent Execution" href="concurrency.html" />
    <link rel="next" title="17.2. multiprocessing — Process-based parallelism" href="multiprocessing.html" />
    <link rel="prev" title="17. Concurrent Execution" href="concurrency.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    <script type="text/javascript" src="../_static/version_switch.js"></script>
    
 

  </head>
  <body>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="multiprocessing.html" title="17.2. multiprocessing — Process-based parallelism"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="concurrency.html" title="17. Concurrent Execution"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &raquo;</li>
        <li>
          <span class="version_switcher_placeholder">3.4.3</span>
          <a href="../index.html">Documentation</a> &raquo;
        </li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="concurrency.html" accesskey="U">17. Concurrent Execution</a> &raquo;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="module-threading">
<span id="threading-thread-based-parallelism"></span><h1>17.1. <a class="reference internal" href="#module-threading" title="threading: Thread-based parallelism."><tt class="xref py py-mod docutils literal"><span class="pre">threading</span></tt></a> &#8212; Thread-based parallelism<a class="headerlink" href="#module-threading" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://hg.python.org/cpython/file/3.4/Lib/threading.py">Lib/threading.py</a></p>
<hr class="docutils" />
<p>This module constructs higher-level threading interfaces on top of the lower
level <a class="reference internal" href="_thread.html#module-_thread" title="_thread: Low-level threading API."><tt class="xref py py-mod docutils literal"><span class="pre">_thread</span></tt></a> module.  See also the <a class="reference internal" href="queue.html#module-queue" title="queue: A synchronized queue class."><tt class="xref py py-mod docutils literal"><span class="pre">queue</span></tt></a> module.</p>
<p>The <a class="reference internal" href="dummy_threading.html#module-dummy_threading" title="dummy_threading: Drop-in replacement for the threading module."><tt class="xref py py-mod docutils literal"><span class="pre">dummy_threading</span></tt></a> module is provided for situations where
<a class="reference internal" href="#module-threading" title="threading: Thread-based parallelism."><tt class="xref py py-mod docutils literal"><span class="pre">threading</span></tt></a> cannot be used because <a class="reference internal" href="_thread.html#module-_thread" title="_thread: Low-level threading API."><tt class="xref py py-mod docutils literal"><span class="pre">_thread</span></tt></a> is missing.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">While they are not listed below, the <tt class="docutils literal"><span class="pre">camelCase</span></tt> names used for some
methods and functions in this module in the Python 2.x series are still
supported by this module.</p>
</div>
<p>This module defines the following functions:</p>
<dl class="function">
<dt id="threading.active_count">
<tt class="descclassname">threading.</tt><tt class="descname">active_count</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.active_count" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of <a class="reference internal" href="#threading.Thread" title="threading.Thread"><tt class="xref py py-class docutils literal"><span class="pre">Thread</span></tt></a> objects currently alive.  The returned
count is equal to the length of the list returned by <a class="reference internal" href="#threading.enumerate" title="threading.enumerate"><tt class="xref py py-func docutils literal"><span class="pre">enumerate()</span></tt></a>.</p>
</dd></dl>

<dl class="function">
<dt id="threading.current_thread">
<tt class="descclassname">threading.</tt><tt class="descname">current_thread</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.current_thread" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current <a class="reference internal" href="#threading.Thread" title="threading.Thread"><tt class="xref py py-class docutils literal"><span class="pre">Thread</span></tt></a> object, corresponding to the caller&#8217;s thread
of control.  If the caller&#8217;s thread of control was not created through the
<a class="reference internal" href="#module-threading" title="threading: Thread-based parallelism."><tt class="xref py py-mod docutils literal"><span class="pre">threading</span></tt></a> module, a dummy thread object with limited functionality is
returned.</p>
</dd></dl>

<dl class="function">
<dt id="threading.get_ident">
<tt class="descclassname">threading.</tt><tt class="descname">get_ident</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.get_ident" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the &#8216;thread identifier&#8217; of the current thread.  This is a nonzero
integer.  Its value has no direct meaning; it is intended as a magic cookie
to be used e.g. to index a dictionary of thread-specific data.  Thread
identifiers may be recycled when a thread exits and another thread is
created.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="threading.enumerate">
<tt class="descclassname">threading.</tt><tt class="descname">enumerate</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.enumerate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all <a class="reference internal" href="#threading.Thread" title="threading.Thread"><tt class="xref py py-class docutils literal"><span class="pre">Thread</span></tt></a> objects currently alive.  The list
includes daemonic threads, dummy thread objects created by
<a class="reference internal" href="#threading.current_thread" title="threading.current_thread"><tt class="xref py py-func docutils literal"><span class="pre">current_thread()</span></tt></a>, and the main thread.  It excludes terminated threads
and threads that have not yet been started.</p>
</dd></dl>

<dl class="function">
<dt id="threading.main_thread">
<tt class="descclassname">threading.</tt><tt class="descname">main_thread</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.main_thread" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the main <a class="reference internal" href="#threading.Thread" title="threading.Thread"><tt class="xref py py-class docutils literal"><span class="pre">Thread</span></tt></a> object.  In normal conditions, the
main thread is the thread from which the Python interpreter was
started.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="threading.settrace">
<tt class="descclassname">threading.</tt><tt class="descname">settrace</tt><big>(</big><em>func</em><big>)</big><a class="headerlink" href="#threading.settrace" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">Set a trace function for all threads started from the <a class="reference internal" href="#module-threading" title="threading: Thread-based parallelism."><tt class="xref py py-mod docutils literal"><span class="pre">threading</span></tt></a> module.
The <em>func</em> will be passed to  <a class="reference internal" href="sys.html#sys.settrace" title="sys.settrace"><tt class="xref py py-func docutils literal"><span class="pre">sys.settrace()</span></tt></a> for each thread, before its
<a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><tt class="xref py py-meth docutils literal"><span class="pre">run()</span></tt></a> method is called.</p>
</dd></dl>

<dl class="function">
<dt id="threading.setprofile">
<tt class="descclassname">threading.</tt><tt class="descname">setprofile</tt><big>(</big><em>func</em><big>)</big><a class="headerlink" href="#threading.setprofile" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Set a profile function for all threads started from the <a class="reference internal" href="#module-threading" title="threading: Thread-based parallelism."><tt class="xref py py-mod docutils literal"><span class="pre">threading</span></tt></a> module.
The <em>func</em> will be passed to  <a class="reference internal" href="sys.html#sys.setprofile" title="sys.setprofile"><tt class="xref py py-func docutils literal"><span class="pre">sys.setprofile()</span></tt></a> for each thread, before its
<a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><tt class="xref py py-meth docutils literal"><span class="pre">run()</span></tt></a> method is called.</p>
</dd></dl>

<dl class="function">
<dt id="threading.stack_size">
<tt class="descclassname">threading.</tt><tt class="descname">stack_size</tt><big>(</big><span class="optional">[</span><em>size</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#threading.stack_size" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the thread stack size used when creating new threads.  The optional
<em>size</em> argument specifies the stack size to be used for subsequently created
threads, and must be 0 (use platform or configured default) or a positive
integer value of at least 32,768 (32 KiB). If <em>size</em> is not specified,
0 is used.  If changing the thread stack size is
unsupported, a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> is raised.  If the specified stack size is
invalid, a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> is raised and the stack size is unmodified.  32 KiB
is currently the minimum supported stack size value to guarantee sufficient
stack space for the interpreter itself.  Note that some platforms may have
particular restrictions on values for the stack size, such as requiring a
minimum stack size &gt; 32 KiB or requiring allocation in multiples of the system
memory page size - platform documentation should be referred to for more
information (4 KiB pages are common; using multiples of 4096 for the stack size is
the suggested approach in the absence of more specific information).
Availability: Windows, systems with POSIX threads.</p>
</dd></dl>

<p>This module also defines the following constant:</p>
<dl class="data">
<dt id="threading.TIMEOUT_MAX">
<tt class="descclassname">threading.</tt><tt class="descname">TIMEOUT_MAX</tt><a class="headerlink" href="#threading.TIMEOUT_MAX" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum value allowed for the <em>timeout</em> parameter of blocking functions
(<a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">Lock.acquire()</span></tt></a>, <a class="reference internal" href="#threading.RLock.acquire" title="threading.RLock.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">RLock.acquire()</span></tt></a>, <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><tt class="xref py py-meth docutils literal"><span class="pre">Condition.wait()</span></tt></a>, etc.).
Specifying a timeout greater than this value will raise an
<a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><tt class="xref py py-exc docutils literal"><span class="pre">OverflowError</span></tt></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.2.</span></p>
</div>
</dd></dl>

<p>This module defines a number of classes, which are detailed in the sections
below.</p>
<p>The design of this module is loosely based on Java&#8217;s threading model. However,
where Java makes locks and condition variables basic behavior of every object,
they are separate objects in Python.  Python&#8217;s <a class="reference internal" href="#threading.Thread" title="threading.Thread"><tt class="xref py py-class docutils literal"><span class="pre">Thread</span></tt></a> class supports a
subset of the behavior of Java&#8217;s Thread class; currently, there are no
priorities, no thread groups, and threads cannot be destroyed, stopped,
suspended, resumed, or interrupted.  The static methods of Java&#8217;s Thread class,
when implemented, are mapped to module-level functions.</p>
<p>All of the methods described below are executed atomically.</p>
<div class="section" id="thread-local-data">
<h2>17.1.1. Thread-Local Data<a class="headerlink" href="#thread-local-data" title="Permalink to this headline">¶</a></h2>
<p>Thread-local data is data whose values are thread specific.  To manage
thread-local data, just create an instance of <a class="reference internal" href="#threading.local" title="threading.local"><tt class="xref py py-class docutils literal"><span class="pre">local</span></tt></a> (or a
subclass) and store attributes on it:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">mydata</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">local</span><span class="p">()</span>
<span class="n">mydata</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>The instance&#8217;s values will be different for separate threads.</p>
<dl class="class">
<dt id="threading.local">
<em class="property">class </em><tt class="descclassname">threading.</tt><tt class="descname">local</tt><a class="headerlink" href="#threading.local" title="Permalink to this definition">¶</a></dt>
<dd><p>A class that represents thread-local data.</p>
<p>For more details and extensive examples, see the documentation string of the
<tt class="xref py py-mod docutils literal"><span class="pre">_threading_local</span></tt> module.</p>
</dd></dl>

</div>
<div class="section" id="thread-objects">
<span id="id1"></span><h2>17.1.2. Thread Objects<a class="headerlink" href="#thread-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#threading.Thread" title="threading.Thread"><tt class="xref py py-class docutils literal"><span class="pre">Thread</span></tt></a> class represents an activity that is run in a separate
thread of control.  There are two ways to specify the activity: by passing a
callable object to the constructor, or by overriding the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><tt class="xref py py-meth docutils literal"><span class="pre">run()</span></tt></a>
method in a subclass.  No other methods (except for the constructor) should be
overridden in a subclass.  In other words, <em>only</em>  override the
<tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt> and <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><tt class="xref py py-meth docutils literal"><span class="pre">run()</span></tt></a> methods of this class.</p>
<p>Once a thread object is created, its activity must be started by calling the
thread&#8217;s <a class="reference internal" href="#threading.Thread.start" title="threading.Thread.start"><tt class="xref py py-meth docutils literal"><span class="pre">start()</span></tt></a> method.  This invokes the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><tt class="xref py py-meth docutils literal"><span class="pre">run()</span></tt></a>
method in a separate thread of control.</p>
<p>Once the thread&#8217;s activity is started, the thread is considered &#8216;alive&#8217;. It
stops being alive when its <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><tt class="xref py py-meth docutils literal"><span class="pre">run()</span></tt></a> method terminates &#8211; either
normally, or by raising an unhandled exception.  The <a class="reference internal" href="#threading.Thread.is_alive" title="threading.Thread.is_alive"><tt class="xref py py-meth docutils literal"><span class="pre">is_alive()</span></tt></a>
method tests whether the thread is alive.</p>
<p>Other threads can call a thread&#8217;s <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt></a> method.  This blocks
the calling thread until the thread whose <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt></a> method is
called is terminated.</p>
<p>A thread has a name.  The name can be passed to the constructor, and read or
changed through the <a class="reference internal" href="#threading.Thread.name" title="threading.Thread.name"><tt class="xref py py-attr docutils literal"><span class="pre">name</span></tt></a> attribute.</p>
<p>A thread can be flagged as a &#8220;daemon thread&#8221;.  The significance of this flag is
that the entire Python program exits when only daemon threads are left.  The
initial value is inherited from the creating thread.  The flag can be set
through the <a class="reference internal" href="#threading.Thread.daemon" title="threading.Thread.daemon"><tt class="xref py py-attr docutils literal"><span class="pre">daemon</span></tt></a> property or the <em>daemon</em> constructor
argument.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Daemon threads are abruptly stopped at shutdown.  Their resources (such
as open files, database transactions, etc.) may not be released properly.
If you want your threads to stop gracefully, make them non-daemonic and
use a suitable signalling mechanism such as an <a class="reference internal" href="#threading.Event" title="threading.Event"><tt class="xref py py-class docutils literal"><span class="pre">Event</span></tt></a>.</p>
</div>
<p>There is a &#8220;main thread&#8221; object; this corresponds to the initial thread of
control in the Python program.  It is not a daemon thread.</p>
<p>There is the possibility that &#8220;dummy thread objects&#8221; are created. These are
thread objects corresponding to &#8220;alien threads&#8221;, which are threads of control
started outside the threading module, such as directly from C code.  Dummy
thread objects have limited functionality; they are always considered alive and
daemonic, and cannot be <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt></a>ed.  They are never deleted,
since it is impossible to detect the termination of alien threads.</p>
<dl class="class">
<dt id="threading.Thread">
<em class="property">class </em><tt class="descclassname">threading.</tt><tt class="descname">Thread</tt><big>(</big><em>group=None</em>, <em>target=None</em>, <em>name=None</em>, <em>args=()</em>, <em>kwargs={}</em>, <em>*</em>, <em>daemon=None</em><big>)</big><a class="headerlink" href="#threading.Thread" title="Permalink to this definition">¶</a></dt>
<dd><p>This constructor should always be called with keyword arguments.  Arguments
are:</p>
<p><em>group</em> should be <tt class="docutils literal"><span class="pre">None</span></tt>; reserved for future extension when a
<tt class="xref py py-class docutils literal"><span class="pre">ThreadGroup</span></tt> class is implemented.</p>
<p><em>target</em> is the callable object to be invoked by the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><tt class="xref py py-meth docutils literal"><span class="pre">run()</span></tt></a> method.
Defaults to <tt class="docutils literal"><span class="pre">None</span></tt>, meaning nothing is called.</p>
<p><em>name</em> is the thread name.  By default, a unique name is constructed of the
form &#8220;Thread-<em>N</em>&#8221; where <em>N</em> is a small decimal number.</p>
<p><em>args</em> is the argument tuple for the target invocation.  Defaults to <tt class="docutils literal"><span class="pre">()</span></tt>.</p>
<p><em>kwargs</em> is a dictionary of keyword arguments for the target invocation.
Defaults to <tt class="docutils literal"><span class="pre">{}</span></tt>.</p>
<p>If not <tt class="docutils literal"><span class="pre">None</span></tt>, <em>daemon</em> explicitly sets whether the thread is daemonic.
If <tt class="docutils literal"><span class="pre">None</span></tt> (the default), the daemonic property is inherited from the
current thread.</p>
<p>If the subclass overrides the constructor, it must make sure to invoke the
base class constructor (<tt class="docutils literal"><span class="pre">Thread.__init__()</span></tt>) before doing anything else to
the thread.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.3: </span>Added the <em>daemon</em> argument.</p>
</div>
<dl class="method">
<dt id="threading.Thread.start">
<tt class="descname">start</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Thread.start" title="Permalink to this definition">¶</a></dt>
<dd><p>Start the thread&#8217;s activity.</p>
<p>It must be called at most once per thread object.  It arranges for the
object&#8217;s <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><tt class="xref py py-meth docutils literal"><span class="pre">run()</span></tt></a> method to be invoked in a separate thread
of control.</p>
<p>This method will raise a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> if called more than once
on the same thread object.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Thread.run">
<tt class="descname">run</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Thread.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Method representing the thread&#8217;s activity.</p>
<p>You may override this method in a subclass.  The standard <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><tt class="xref py py-meth docutils literal"><span class="pre">run()</span></tt></a>
method invokes the callable object passed to the object&#8217;s constructor as
the <em>target</em> argument, if any, with sequential and keyword arguments taken
from the <em>args</em> and <em>kwargs</em> arguments, respectively.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Thread.join">
<tt class="descname">join</tt><big>(</big><em>timeout=None</em><big>)</big><a class="headerlink" href="#threading.Thread.join" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait until the thread terminates. This blocks the calling thread until
the thread whose <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt></a> method is called terminates &#8211; either
normally or through an unhandled exception &#8211;, or until the optional
timeout occurs.</p>
<p>When the <em>timeout</em> argument is present and not <tt class="docutils literal"><span class="pre">None</span></tt>, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). As <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt></a> always returns <tt class="docutils literal"><span class="pre">None</span></tt>,
you must call <a class="reference internal" href="#threading.Thread.is_alive" title="threading.Thread.is_alive"><tt class="xref py py-meth docutils literal"><span class="pre">is_alive()</span></tt></a> after <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt></a> to
decide whether a timeout happened &#8211; if the thread is still alive, the
<a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt></a> call timed out.</p>
<p>When the <em>timeout</em> argument is not present or <tt class="docutils literal"><span class="pre">None</span></tt>, the operation will
block until the thread terminates.</p>
<p>A thread can be <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt></a>ed many times.</p>
<p><a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt></a> raises a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> if an attempt is made
to join the current thread as that would cause a deadlock. It is also
an error to <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt></a> a thread before it has been started
and attempts to do so raise the same exception.</p>
</dd></dl>

<dl class="attribute">
<dt id="threading.Thread.name">
<tt class="descname">name</tt><a class="headerlink" href="#threading.Thread.name" title="Permalink to this definition">¶</a></dt>
<dd><p>A string used for identification purposes only. It has no semantics.
Multiple threads may be given the same name.  The initial name is set by
the constructor.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Thread.getName">
<tt class="descname">getName</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Thread.getName" title="Permalink to this definition">¶</a></dt>
<dt id="threading.Thread.setName">
<tt class="descname">setName</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Thread.setName" title="Permalink to this definition">¶</a></dt>
<dd><p>Old getter/setter API for <a class="reference internal" href="#threading.Thread.name" title="threading.Thread.name"><tt class="xref py py-attr docutils literal"><span class="pre">name</span></tt></a>; use it directly as a
property instead.</p>
</dd></dl>

<dl class="attribute">
<dt id="threading.Thread.ident">
<tt class="descname">ident</tt><a class="headerlink" href="#threading.Thread.ident" title="Permalink to this definition">¶</a></dt>
<dd><p>The &#8216;thread identifier&#8217; of this thread or <tt class="docutils literal"><span class="pre">None</span></tt> if the thread has not
been started.  This is a nonzero integer.  See the
<a class="reference internal" href="_thread.html#_thread.get_ident" title="_thread.get_ident"><tt class="xref py py-func docutils literal"><span class="pre">_thread.get_ident()</span></tt></a> function.  Thread identifiers may be recycled
when a thread exits and another thread is created.  The identifier is
available even after the thread has exited.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Thread.is_alive">
<tt class="descname">is_alive</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Thread.is_alive" title="Permalink to this definition">¶</a></dt>
<dd><p>Return whether the thread is alive.</p>
<p>This method returns <tt class="docutils literal"><span class="pre">True</span></tt> just before the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><tt class="xref py py-meth docutils literal"><span class="pre">run()</span></tt></a> method
starts until just after the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><tt class="xref py py-meth docutils literal"><span class="pre">run()</span></tt></a> method terminates.  The
module function <a class="reference internal" href="#threading.enumerate" title="threading.enumerate"><tt class="xref py py-func docutils literal"><span class="pre">enumerate()</span></tt></a> returns a list of all alive threads.</p>
</dd></dl>

<dl class="attribute">
<dt id="threading.Thread.daemon">
<tt class="descname">daemon</tt><a class="headerlink" href="#threading.Thread.daemon" title="Permalink to this definition">¶</a></dt>
<dd><p>A boolean value indicating whether this thread is a daemon thread (True)
or not (False).  This must be set before <a class="reference internal" href="#threading.Thread.start" title="threading.Thread.start"><tt class="xref py py-meth docutils literal"><span class="pre">start()</span></tt></a> is called,
otherwise <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> is raised.  Its initial value is inherited
from the creating thread; the main thread is not a daemon thread and
therefore all threads created in the main thread default to
<a class="reference internal" href="#threading.Thread.daemon" title="threading.Thread.daemon"><tt class="xref py py-attr docutils literal"><span class="pre">daemon</span></tt></a> = <tt class="docutils literal"><span class="pre">False</span></tt>.</p>
<p>The entire Python program exits when no alive non-daemon threads are left.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Thread.isDaemon">
<tt class="descname">isDaemon</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Thread.isDaemon" title="Permalink to this definition">¶</a></dt>
<dt id="threading.Thread.setDaemon">
<tt class="descname">setDaemon</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Thread.setDaemon" title="Permalink to this definition">¶</a></dt>
<dd><p>Old getter/setter API for <a class="reference internal" href="#threading.Thread.daemon" title="threading.Thread.daemon"><tt class="xref py py-attr docutils literal"><span class="pre">daemon</span></tt></a>; use it directly as a
property instead.</p>
</dd></dl>

</dd></dl>

<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> In CPython, due to the <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><em class="xref std std-term">Global Interpreter Lock</em></a>, only one thread
can execute Python code at once (even though certain performance-oriented
libraries might overcome this limitation).
If you want your application to make better use of the computational
resources of multi-core machines, you are advised to use
<a class="reference internal" href="multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><tt class="xref py py-mod docutils literal"><span class="pre">multiprocessing</span></tt></a> or <a class="reference internal" href="concurrent.futures.html#concurrent.futures.ProcessPoolExecutor" title="concurrent.futures.ProcessPoolExecutor"><tt class="xref py py-class docutils literal"><span class="pre">concurrent.futures.ProcessPoolExecutor</span></tt></a>.
However, threading is still an appropriate model if you want to run
multiple I/O-bound tasks simultaneously.</p>
</div>
</div>
<div class="section" id="lock-objects">
<span id="id2"></span><h2>17.1.3. Lock Objects<a class="headerlink" href="#lock-objects" title="Permalink to this headline">¶</a></h2>
<p>A primitive lock is a synchronization primitive that is not owned by a
particular thread when locked.  In Python, it is currently the lowest level
synchronization primitive available, implemented directly by the <a class="reference internal" href="_thread.html#module-_thread" title="_thread: Low-level threading API."><tt class="xref py py-mod docutils literal"><span class="pre">_thread</span></tt></a>
extension module.</p>
<p>A primitive lock is in one of two states, &#8220;locked&#8221; or &#8220;unlocked&#8221;. It is created
in the unlocked state.  It has two basic methods, <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a> and
<a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a>.  When the state is unlocked, <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a>
changes the state to locked and returns immediately.  When the state is locked,
<a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a> blocks until a call to <a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a> in another
thread changes it to unlocked, then the <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a> call resets it
to locked and returns.  The <a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a> method should only be
called in the locked state; it changes the state to unlocked and returns
immediately. If an attempt is made to release an unlocked lock, a
<a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> will be raised.</p>
<p>Locks also support the <a class="reference internal" href="#with-locks"><em>context management protocol</em></a>.</p>
<p>When more than one thread is blocked in <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a> waiting for the
state to turn to unlocked, only one thread proceeds when a <a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a>
call resets the state to unlocked; which one of the waiting threads proceeds
is not defined, and may vary across implementations.</p>
<p>All methods are executed atomically.</p>
<dl class="class">
<dt id="threading.Lock">
<em class="property">class </em><tt class="descclassname">threading.</tt><tt class="descname">Lock</tt><a class="headerlink" href="#threading.Lock" title="Permalink to this definition">¶</a></dt>
<dd><p>The class implementing primitive lock objects.  Once a thread has acquired a
lock, subsequent attempts to acquire it block, until it is released; any
thread may release it.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.3: </span>Changed from a factory function to a class.</p>
</div>
<dl class="method">
<dt id="threading.Lock.acquire">
<tt class="descname">acquire</tt><big>(</big><em>blocking=True</em>, <em>timeout=-1</em><big>)</big><a class="headerlink" href="#threading.Lock.acquire" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire a lock, blocking or non-blocking.</p>
<p>When invoked with the <em>blocking</em> argument set to <tt class="docutils literal"><span class="pre">True</span></tt> (the default),
block until the lock is unlocked, then set it to locked and return <tt class="docutils literal"><span class="pre">True</span></tt>.</p>
<p>When invoked with the <em>blocking</em> argument set to <tt class="docutils literal"><span class="pre">False</span></tt>, do not block.
If a call with <em>blocking</em> set to <tt class="docutils literal"><span class="pre">True</span></tt> would block, return <tt class="docutils literal"><span class="pre">False</span></tt>
immediately; otherwise, set the lock to locked and return <tt class="docutils literal"><span class="pre">True</span></tt>.</p>
<p>When invoked with the floating-point <em>timeout</em> argument set to a positive
value, block for at most the number of seconds specified by <em>timeout</em>
and as long as the lock cannot be acquired.  A <em>timeout</em> argument of <tt class="docutils literal"><span class="pre">-1</span></tt>
specifies an unbounded wait.  It is forbidden to specify a <em>timeout</em>
when <em>blocking</em> is false.</p>
<p>The return value is <tt class="docutils literal"><span class="pre">True</span></tt> if the lock is acquired successfully,
<tt class="docutils literal"><span class="pre">False</span></tt> if not (for example if the <em>timeout</em> expired).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.2: </span>The <em>timeout</em> parameter is new.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.2: </span>Lock acquires can now be interrupted by signals on POSIX.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="threading.Lock.release">
<tt class="descname">release</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Lock.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release a lock.  This can be called from any thread, not only the thread
which has acquired the lock.</p>
<p>When the lock is locked, reset it to unlocked, and return.  If any other threads
are blocked waiting for the lock to become unlocked, allow exactly one of them
to proceed.</p>
<p>When invoked on an unlocked lock, a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> is raised.</p>
<p>There is no return value.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="rlock-objects">
<span id="id3"></span><h2>17.1.4. RLock Objects<a class="headerlink" href="#rlock-objects" title="Permalink to this headline">¶</a></h2>
<p>A reentrant lock is a synchronization primitive that may be acquired multiple
times by the same thread.  Internally, it uses the concepts of &#8220;owning thread&#8221;
and &#8220;recursion level&#8221; in addition to the locked/unlocked state used by primitive
locks.  In the locked state, some thread owns the lock; in the unlocked state,
no thread owns it.</p>
<p>To lock the lock, a thread calls its <a class="reference internal" href="#threading.RLock.acquire" title="threading.RLock.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a> method; this
returns once the thread owns the lock.  To unlock the lock, a thread calls
its <a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a> method. <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a>/<a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a>
call pairs may be nested; only the final <a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a> (the
<a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a> of the outermost pair) resets the lock to unlocked and
allows another thread blocked in <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a> to proceed.</p>
<p>Reentrant locks also support the <a class="reference internal" href="#with-locks"><em>context management protocol</em></a>.</p>
<dl class="class">
<dt id="threading.RLock">
<em class="property">class </em><tt class="descclassname">threading.</tt><tt class="descname">RLock</tt><a class="headerlink" href="#threading.RLock" title="Permalink to this definition">¶</a></dt>
<dd><p>This class implements reentrant lock objects.  A reentrant lock must be
released by the thread that acquired it.  Once a thread has acquired a
reentrant lock, the same thread may acquire it again without blocking; the
thread must release it once for each time it has acquired it.</p>
<p>Note that <tt class="docutils literal"><span class="pre">RLock</span></tt> is actually a factory function which returns an instance
of the most efficient version of the concrete RLock class that is supported
by the platform.</p>
<dl class="method">
<dt id="threading.RLock.acquire">
<tt class="descname">acquire</tt><big>(</big><em>blocking=True</em>, <em>timeout=-1</em><big>)</big><a class="headerlink" href="#threading.RLock.acquire" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire a lock, blocking or non-blocking.</p>
<p>When invoked without arguments: if this thread already owns the lock, increment
the recursion level by one, and return immediately.  Otherwise, if another
thread owns the lock, block until the lock is unlocked.  Once the lock is
unlocked (not owned by any thread), then grab ownership, set the recursion level
to one, and return.  If more than one thread is blocked waiting until the lock
is unlocked, only one at a time will be able to grab ownership of the lock.
There is no return value in this case.</p>
<p>When invoked with the <em>blocking</em> argument set to true, do the same thing as when
called without arguments, and return true.</p>
<p>When invoked with the <em>blocking</em> argument set to false, do not block.  If a call
without an argument would block, return false immediately; otherwise, do the
same thing as when called without arguments, and return true.</p>
<p>When invoked with the floating-point <em>timeout</em> argument set to a positive
value, block for at most the number of seconds specified by <em>timeout</em>
and as long as the lock cannot be acquired.  Return true if the lock has
been acquired, false if the timeout has elapsed.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.2: </span>The <em>timeout</em> parameter is new.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="threading.RLock.release">
<tt class="descname">release</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.RLock.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release a lock, decrementing the recursion level.  If after the decrement it is
zero, reset the lock to unlocked (not owned by any thread), and if any other
threads are blocked waiting for the lock to become unlocked, allow exactly one
of them to proceed.  If after the decrement the recursion level is still
nonzero, the lock remains locked and owned by the calling thread.</p>
<p>Only call this method when the calling thread owns the lock. A
<a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> is raised if this method is called when the lock is
unlocked.</p>
<p>There is no return value.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="condition-objects">
<span id="id4"></span><h2>17.1.5. Condition Objects<a class="headerlink" href="#condition-objects" title="Permalink to this headline">¶</a></h2>
<p>A condition variable is always associated with some kind of lock; this can be
passed in or one will be created by default.  Passing one in is useful when
several condition variables must share the same lock.  The lock is part of
the condition object: you don&#8217;t have to track it separately.</p>
<p>A condition variable obeys the <a class="reference internal" href="#with-locks"><em>context management protocol</em></a>:
using the <tt class="docutils literal"><span class="pre">with</span></tt> statement acquires the associated lock for the duration of
the enclosed block.  The <a class="reference internal" href="#threading.Condition.acquire" title="threading.Condition.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a> and
<a class="reference internal" href="#threading.Condition.release" title="threading.Condition.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a> methods also call the corresponding methods of
the associated lock.</p>
<p>Other methods must be called with the associated lock held.  The
<a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a> method releases the lock, and then blocks until
another thread awakens it by calling <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><tt class="xref py py-meth docutils literal"><span class="pre">notify()</span></tt></a> or
<a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><tt class="xref py py-meth docutils literal"><span class="pre">notify_all()</span></tt></a>.  Once awakened, <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a>
re-acquires the lock and returns.  It is also possible to specify a timeout.</p>
<p>The <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><tt class="xref py py-meth docutils literal"><span class="pre">notify()</span></tt></a> method wakes up one of the threads waiting for
the condition variable, if any are waiting.  The <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><tt class="xref py py-meth docutils literal"><span class="pre">notify_all()</span></tt></a>
method wakes up all threads waiting for the condition variable.</p>
<p>Note: the <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><tt class="xref py py-meth docutils literal"><span class="pre">notify()</span></tt></a> and <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><tt class="xref py py-meth docutils literal"><span class="pre">notify_all()</span></tt></a> methods
don&#8217;t release the lock; this means that the thread or threads awakened will
not return from their <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a> call immediately, but only when
the thread that called <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><tt class="xref py py-meth docutils literal"><span class="pre">notify()</span></tt></a> or <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><tt class="xref py py-meth docutils literal"><span class="pre">notify_all()</span></tt></a>
finally relinquishes ownership of the lock.</p>
<p>The typical programming style using condition variables uses the lock to
synchronize access to some shared state; threads that are interested in a
particular change of state call <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a> repeatedly until they
see the desired state, while threads that modify the state call
<a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><tt class="xref py py-meth docutils literal"><span class="pre">notify()</span></tt></a> or <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><tt class="xref py py-meth docutils literal"><span class="pre">notify_all()</span></tt></a> when they change
the state in such a way that it could possibly be a desired state for one
of the waiters.  For example, the following code is a generic
producer-consumer situation with unlimited buffer capacity:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="c"># Consume one item</span>
<span class="k">with</span> <span class="n">cv</span><span class="p">:</span>
    <span class="k">while</span> <span class="ow">not</span> <span class="n">an_item_is_available</span><span class="p">():</span>
        <span class="n">cv</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
    <span class="n">get_an_available_item</span><span class="p">()</span>

<span class="c"># Produce one item</span>
<span class="k">with</span> <span class="n">cv</span><span class="p">:</span>
    <span class="n">make_an_item_available</span><span class="p">()</span>
    <span class="n">cv</span><span class="o">.</span><span class="n">notify</span><span class="p">()</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">while</span></tt> loop checking for the application&#8217;s condition is necessary
because <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a> can return after an arbitrary long time,
and the condition which prompted the <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><tt class="xref py py-meth docutils literal"><span class="pre">notify()</span></tt></a> call may
no longer hold true.  This is inherent to multi-threaded programming.  The
<a class="reference internal" href="#threading.Condition.wait_for" title="threading.Condition.wait_for"><tt class="xref py py-meth docutils literal"><span class="pre">wait_for()</span></tt></a> method can be used to automate the condition
checking, and eases the computation of timeouts:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="c"># Consume an item</span>
<span class="k">with</span> <span class="n">cv</span><span class="p">:</span>
    <span class="n">cv</span><span class="o">.</span><span class="n">wait_for</span><span class="p">(</span><span class="n">an_item_is_available</span><span class="p">)</span>
    <span class="n">get_an_available_item</span><span class="p">()</span>
</pre></div>
</div>
<p>To choose between <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><tt class="xref py py-meth docutils literal"><span class="pre">notify()</span></tt></a> and <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><tt class="xref py py-meth docutils literal"><span class="pre">notify_all()</span></tt></a>,
consider whether one state change can be interesting for only one or several
waiting threads.  E.g. in a typical producer-consumer situation, adding one
item to the buffer only needs to wake up one consumer thread.</p>
<dl class="class">
<dt id="threading.Condition">
<em class="property">class </em><tt class="descclassname">threading.</tt><tt class="descname">Condition</tt><big>(</big><em>lock=None</em><big>)</big><a class="headerlink" href="#threading.Condition" title="Permalink to this definition">¶</a></dt>
<dd><p>This class implements condition variable objects.  A condition variable
allows one or more threads to wait until they are notified by another thread.</p>
<p>If the <em>lock</em> argument is given and not <tt class="docutils literal"><span class="pre">None</span></tt>, it must be a <a class="reference internal" href="#threading.Lock" title="threading.Lock"><tt class="xref py py-class docutils literal"><span class="pre">Lock</span></tt></a>
or <a class="reference internal" href="#threading.RLock" title="threading.RLock"><tt class="xref py py-class docutils literal"><span class="pre">RLock</span></tt></a> object, and it is used as the underlying lock.  Otherwise,
a new <a class="reference internal" href="#threading.RLock" title="threading.RLock"><tt class="xref py py-class docutils literal"><span class="pre">RLock</span></tt></a> object is created and used as the underlying lock.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.3: </span>changed from a factory function to a class.</p>
</div>
<dl class="method">
<dt id="threading.Condition.acquire">
<tt class="descname">acquire</tt><big>(</big><em>*args</em><big>)</big><a class="headerlink" href="#threading.Condition.acquire" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire the underlying lock. This method calls the corresponding method on
the underlying lock; the return value is whatever that method returns.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Condition.release">
<tt class="descname">release</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Condition.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release the underlying lock. This method calls the corresponding method on
the underlying lock; there is no return value.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Condition.wait">
<tt class="descname">wait</tt><big>(</big><em>timeout=None</em><big>)</big><a class="headerlink" href="#threading.Condition.wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait until notified or until a timeout occurs. If the calling thread has
not acquired the lock when this method is called, a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> is
raised.</p>
<p>This method releases the underlying lock, and then blocks until it is
awakened by a <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><tt class="xref py py-meth docutils literal"><span class="pre">notify()</span></tt></a> or <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><tt class="xref py py-meth docutils literal"><span class="pre">notify_all()</span></tt></a> call for the same
condition variable in another thread, or until the optional timeout
occurs.  Once awakened or timed out, it re-acquires the lock and returns.</p>
<p>When the <em>timeout</em> argument is present and not <tt class="docutils literal"><span class="pre">None</span></tt>, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).</p>
<p>When the underlying lock is an <a class="reference internal" href="#threading.RLock" title="threading.RLock"><tt class="xref py py-class docutils literal"><span class="pre">RLock</span></tt></a>, it is not released using
its <a class="reference internal" href="#threading.Condition.release" title="threading.Condition.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a> method, since this may not actually unlock the lock
when it was acquired multiple times recursively.  Instead, an internal
interface of the <a class="reference internal" href="#threading.RLock" title="threading.RLock"><tt class="xref py py-class docutils literal"><span class="pre">RLock</span></tt></a> class is used, which really unlocks it
even when it has been recursively acquired several times. Another internal
interface is then used to restore the recursion level when the lock is
reacquired.</p>
<p>The return value is <tt class="docutils literal"><span class="pre">True</span></tt> unless a given <em>timeout</em> expired, in which
case it is <tt class="docutils literal"><span class="pre">False</span></tt>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.2: </span>Previously, the method always returned <tt class="docutils literal"><span class="pre">None</span></tt>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="threading.Condition.wait_for">
<tt class="descname">wait_for</tt><big>(</big><em>predicate</em>, <em>timeout=None</em><big>)</big><a class="headerlink" href="#threading.Condition.wait_for" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait until a condition evaluates to True.  <em>predicate</em> should be a
callable which result will be interpreted as a boolean value.
A <em>timeout</em> may be provided giving the maximum time to wait.</p>
<p>This utility method may call <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a> repeatedly until the predicate
is satisfied, or until a timeout occurs. The return value is
the last return value of the predicate and will evaluate to
<tt class="docutils literal"><span class="pre">False</span></tt> if the method timed out.</p>
<p>Ignoring the timeout feature, calling this method is roughly equivalent to
writing:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">while</span> <span class="ow">not</span> <span class="n">predicate</span><span class="p">():</span>
    <span class="n">cv</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
</pre></div>
</div>
<p>Therefore, the same rules apply as with <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a>: The lock must be
held when called and is re-acquired on return.  The predicate is evaluated
with the lock held.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="threading.Condition.notify">
<tt class="descname">notify</tt><big>(</big><em>n=1</em><big>)</big><a class="headerlink" href="#threading.Condition.notify" title="Permalink to this definition">¶</a></dt>
<dd><p>By default, wake up one thread waiting on this condition, if any.  If the
calling thread has not acquired the lock when this method is called, a
<a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> is raised.</p>
<p>This method wakes up at most <em>n</em> of the threads waiting for the condition
variable; it is a no-op if no threads are waiting.</p>
<p>The current implementation wakes up exactly <em>n</em> threads, if at least <em>n</em>
threads are waiting.  However, it&#8217;s not safe to rely on this behavior.
A future, optimized implementation may occasionally wake up more than
<em>n</em> threads.</p>
<p>Note: an awakened thread does not actually return from its <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a>
call until it can reacquire the lock.  Since <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><tt class="xref py py-meth docutils literal"><span class="pre">notify()</span></tt></a> does not
release the lock, its caller should.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Condition.notify_all">
<tt class="descname">notify_all</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Condition.notify_all" title="Permalink to this definition">¶</a></dt>
<dd><p>Wake up all threads waiting on this condition.  This method acts like
<a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><tt class="xref py py-meth docutils literal"><span class="pre">notify()</span></tt></a>, but wakes up all waiting threads instead of one. If the
calling thread has not acquired the lock when this method is called, a
<a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> is raised.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="semaphore-objects">
<span id="id5"></span><h2>17.1.6. Semaphore Objects<a class="headerlink" href="#semaphore-objects" title="Permalink to this headline">¶</a></h2>
<p>This is one of the oldest synchronization primitives in the history of computer
science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
used the names <tt class="docutils literal"><span class="pre">P()</span></tt> and <tt class="docutils literal"><span class="pre">V()</span></tt> instead of <a class="reference internal" href="#threading.Semaphore.acquire" title="threading.Semaphore.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a> and
<a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a>).</p>
<p>A semaphore manages an internal counter which is decremented by each
<a class="reference internal" href="#threading.Semaphore.acquire" title="threading.Semaphore.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a> call and incremented by each <a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a>
call.  The counter can never go below zero; when <a class="reference internal" href="#threading.Semaphore.acquire" title="threading.Semaphore.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a>
finds that it is zero, it blocks, waiting until some other thread calls
<a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a>.</p>
<p>Semaphores also support the <a class="reference internal" href="#with-locks"><em>context management protocol</em></a>.</p>
<dl class="class">
<dt id="threading.Semaphore">
<em class="property">class </em><tt class="descclassname">threading.</tt><tt class="descname">Semaphore</tt><big>(</big><em>value=1</em><big>)</big><a class="headerlink" href="#threading.Semaphore" title="Permalink to this definition">¶</a></dt>
<dd><p>This class implements semaphore objects.  A semaphore manages a counter
representing the number of <a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a> calls minus the number of
<a class="reference internal" href="#threading.Semaphore.acquire" title="threading.Semaphore.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a> calls, plus an initial value.  The <a class="reference internal" href="#threading.Semaphore.acquire" title="threading.Semaphore.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a> method
blocks if necessary until it can return without making the counter negative.
If not given, <em>value</em> defaults to 1.</p>
<p>The optional argument gives the initial <em>value</em> for the internal counter; it
defaults to <tt class="docutils literal"><span class="pre">1</span></tt>. If the <em>value</em> given is less than 0, <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> is
raised.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.3: </span>changed from a factory function to a class.</p>
</div>
<dl class="method">
<dt id="threading.Semaphore.acquire">
<tt class="descname">acquire</tt><big>(</big><em>blocking=True</em>, <em>timeout=None</em><big>)</big><a class="headerlink" href="#threading.Semaphore.acquire" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire a semaphore.</p>
<p>When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately.  If it is zero
on entry, block, waiting until some other thread has called
<a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a> to make it larger than zero.  This is done
with proper interlocking so that if multiple <a class="reference internal" href="#threading.Semaphore.acquire" title="threading.Semaphore.acquire"><tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt></a> calls are
blocked, <a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt></a> will wake exactly one of them up.
The implementation may pick one at random, so the order in which
blocked threads are awakened should not be relied on.  Returns
true (or blocks indefinitely).</p>
<p>When invoked with <em>blocking</em> set to false, do not block.  If a call
without an argument would block, return false immediately; otherwise,
do the same thing as when called without arguments, and return true.</p>
<p>When invoked with a <em>timeout</em> other than None, it will block for at
most <em>timeout</em> seconds.  If acquire does not complete successfully in
that interval, return false.  Return true otherwise.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.2: </span>The <em>timeout</em> parameter is new.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="threading.Semaphore.release">
<tt class="descname">release</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Semaphore.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release a semaphore, incrementing the internal counter by one.  When it
was zero on entry and another thread is waiting for it to become larger
than zero again, wake up that thread.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="threading.BoundedSemaphore">
<em class="property">class </em><tt class="descclassname">threading.</tt><tt class="descname">BoundedSemaphore</tt><big>(</big><em>value=1</em><big>)</big><a class="headerlink" href="#threading.BoundedSemaphore" title="Permalink to this definition">¶</a></dt>
<dd><p>Class implementing bounded semaphore objects.  A bounded semaphore checks to
make sure its current value doesn&#8217;t exceed its initial value.  If it does,
<a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> is raised. In most situations semaphores are used to guard
resources with limited capacity.  If the semaphore is released too many times
it&#8217;s a sign of a bug.  If not given, <em>value</em> defaults to 1.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.3: </span>changed from a factory function to a class.</p>
</div>
</dd></dl>

<div class="section" id="semaphore-example">
<span id="semaphore-examples"></span><h3>17.1.6.1. <a class="reference internal" href="#threading.Semaphore" title="threading.Semaphore"><tt class="xref py py-class docutils literal"><span class="pre">Semaphore</span></tt></a> Example<a class="headerlink" href="#semaphore-example" title="Permalink to this headline">¶</a></h3>
<p>Semaphores are often used to guard resources with limited capacity, for example,
a database server.  In any situation where the size of the resource is fixed,
you should use a bounded semaphore.  Before spawning any worker threads, your
main thread would initialize the semaphore:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">maxconnections</span> <span class="o">=</span> <span class="mi">5</span>
<span class="c"># ...</span>
<span class="n">pool_sema</span> <span class="o">=</span> <span class="n">BoundedSemaphore</span><span class="p">(</span><span class="n">value</span><span class="o">=</span><span class="n">maxconnections</span><span class="p">)</span>
</pre></div>
</div>
<p>Once spawned, worker threads call the semaphore&#8217;s acquire and release methods
when they need to connect to the server:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">with</span> <span class="n">pool_sema</span><span class="p">:</span>
    <span class="n">conn</span> <span class="o">=</span> <span class="n">connectdb</span><span class="p">()</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="c"># ... use connection ...</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="n">conn</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The use of a bounded semaphore reduces the chance that a programming error which
causes the semaphore to be released more than it&#8217;s acquired will go undetected.</p>
</div>
</div>
<div class="section" id="event-objects">
<span id="id6"></span><h2>17.1.7. Event Objects<a class="headerlink" href="#event-objects" title="Permalink to this headline">¶</a></h2>
<p>This is one of the simplest mechanisms for communication between threads: one
thread signals an event and other threads wait for it.</p>
<p>An event object manages an internal flag that can be set to true with the
<a class="reference internal" href="#threading.Event.set" title="threading.Event.set"><tt class="xref py py-meth docutils literal"><span class="pre">set()</span></tt></a> method and reset to false with the <a class="reference internal" href="#threading.Event.clear" title="threading.Event.clear"><tt class="xref py py-meth docutils literal"><span class="pre">clear()</span></tt></a>
method.  The <a class="reference internal" href="#threading.Event.wait" title="threading.Event.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a> method blocks until the flag is true.</p>
<dl class="class">
<dt id="threading.Event">
<em class="property">class </em><tt class="descclassname">threading.</tt><tt class="descname">Event</tt><a class="headerlink" href="#threading.Event" title="Permalink to this definition">¶</a></dt>
<dd><p>Class implementing event objects.  An event manages a flag that can be set to
true with the <a class="reference internal" href="#threading.Event.set" title="threading.Event.set"><tt class="xref py py-meth docutils literal"><span class="pre">set()</span></tt></a> method and reset to false with the
<a class="reference internal" href="#threading.Event.clear" title="threading.Event.clear"><tt class="xref py py-meth docutils literal"><span class="pre">clear()</span></tt></a> method.  The <a class="reference internal" href="#threading.Event.wait" title="threading.Event.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a> method blocks until the flag is true.
The flag is initially false.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.3: </span>changed from a factory function to a class.</p>
</div>
<dl class="method">
<dt id="threading.Event.is_set">
<tt class="descname">is_set</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Event.is_set" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if and only if the internal flag is true.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Event.set">
<tt class="descname">set</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Event.set" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the internal flag to true. All threads waiting for it to become true
are awakened. Threads that call <a class="reference internal" href="#threading.Event.wait" title="threading.Event.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a> once the flag is true will
not block at all.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Event.clear">
<tt class="descname">clear</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Event.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset the internal flag to false. Subsequently, threads calling
<a class="reference internal" href="#threading.Event.wait" title="threading.Event.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a> will block until <a class="reference internal" href="#threading.Event.set" title="threading.Event.set"><tt class="xref py py-meth docutils literal"><span class="pre">set()</span></tt></a> is called to set the internal
flag to true again.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Event.wait">
<tt class="descname">wait</tt><big>(</big><em>timeout=None</em><big>)</big><a class="headerlink" href="#threading.Event.wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Block until the internal flag is true.  If the internal flag is true on
entry, return immediately.  Otherwise, block until another thread calls
<a class="reference internal" href="#threading.Event.set" title="threading.Event.set"><tt class="xref py py-meth docutils literal"><span class="pre">set()</span></tt></a> to set the flag to true, or until the optional timeout occurs.</p>
<p>When the timeout argument is present and not <tt class="docutils literal"><span class="pre">None</span></tt>, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).</p>
<p>This method returns true if and only if the internal flag has been set to
true, either before the wait call or after the wait starts, so it will
always return <tt class="docutils literal"><span class="pre">True</span></tt> except if a timeout is given and the operation
times out.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.1: </span>Previously, the method always returned <tt class="docutils literal"><span class="pre">None</span></tt>.</p>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="timer-objects">
<span id="id7"></span><h2>17.1.8. Timer Objects<a class="headerlink" href="#timer-objects" title="Permalink to this headline">¶</a></h2>
<p>This class represents an action that should be run only after a certain amount
of time has passed &#8212; a timer.  <a class="reference internal" href="#threading.Timer" title="threading.Timer"><tt class="xref py py-class docutils literal"><span class="pre">Timer</span></tt></a> is a subclass of <a class="reference internal" href="#threading.Thread" title="threading.Thread"><tt class="xref py py-class docutils literal"><span class="pre">Thread</span></tt></a>
and as such also functions as an example of creating custom threads.</p>
<p>Timers are started, as with threads, by calling their <tt class="xref py py-meth docutils literal"><span class="pre">start()</span></tt>
method.  The timer can be stopped (before its action has begun) by calling the
<a class="reference internal" href="#threading.Timer.cancel" title="threading.Timer.cancel"><tt class="xref py py-meth docutils literal"><span class="pre">cancel()</span></tt></a> method.  The interval the timer will wait before
executing its action may not be exactly the same as the interval specified by
the user.</p>
<p>For example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">hello</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;hello, world&quot;</span><span class="p">)</span>

<span class="n">t</span> <span class="o">=</span> <span class="n">Timer</span><span class="p">(</span><span class="mf">30.0</span><span class="p">,</span> <span class="n">hello</span><span class="p">)</span>
<span class="n">t</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="c"># after 30 seconds, &quot;hello, world&quot; will be printed</span>
</pre></div>
</div>
<dl class="class">
<dt id="threading.Timer">
<em class="property">class </em><tt class="descclassname">threading.</tt><tt class="descname">Timer</tt><big>(</big><em>interval</em>, <em>function</em>, <em>args=None</em>, <em>kwargs=None</em><big>)</big><a class="headerlink" href="#threading.Timer" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a timer that will run <em>function</em> with arguments <em>args</em> and  keyword
arguments <em>kwargs</em>, after <em>interval</em> seconds have passed.
If <em>args</em> is None (the default) then an empty list will be used.
If <em>kwargs</em> is None (the default) then an empty dict will be used.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.3: </span>changed from a factory function to a class.</p>
</div>
<dl class="method">
<dt id="threading.Timer.cancel">
<tt class="descname">cancel</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Timer.cancel" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop the timer, and cancel the execution of the timer&#8217;s action.  This will
only work if the timer is still in its waiting stage.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="barrier-objects">
<h2>17.1.9. Barrier Objects<a class="headerlink" href="#barrier-objects" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.2.</span></p>
</div>
<p>This class provides a simple synchronization primitive for use by a fixed number
of threads that need to wait for each other.  Each of the threads tries to pass
the barrier by calling the <a class="reference internal" href="#threading.Barrier.wait" title="threading.Barrier.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a> method and will block until
all of the threads have made the call.  At this points, the threads are released
simultaneously.</p>
<p>The barrier can be reused any number of times for the same number of threads.</p>
<p>As an example, here is a simple way to synchronize a client and server thread:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">b</span> <span class="o">=</span> <span class="n">Barrier</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">server</span><span class="p">():</span>
    <span class="n">start_server</span><span class="p">()</span>
    <span class="n">b</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
    <span class="k">while</span> <span class="k">True</span><span class="p">:</span>
        <span class="n">connection</span> <span class="o">=</span> <span class="n">accept_connection</span><span class="p">()</span>
        <span class="n">process_server_connection</span><span class="p">(</span><span class="n">connection</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">client</span><span class="p">():</span>
    <span class="n">b</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
    <span class="k">while</span> <span class="k">True</span><span class="p">:</span>
        <span class="n">connection</span> <span class="o">=</span> <span class="n">make_connection</span><span class="p">()</span>
        <span class="n">process_client_connection</span><span class="p">(</span><span class="n">connection</span><span class="p">)</span>
</pre></div>
</div>
<dl class="class">
<dt id="threading.Barrier">
<em class="property">class </em><tt class="descclassname">threading.</tt><tt class="descname">Barrier</tt><big>(</big><em>parties</em>, <em>action=None</em>, <em>timeout=None</em><big>)</big><a class="headerlink" href="#threading.Barrier" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a barrier object for <em>parties</em> number of threads.  An <em>action</em>, when
provided, is a callable to be called by one of the threads when they are
released.  <em>timeout</em> is the default timeout value if none is specified for
the <a class="reference internal" href="#threading.Barrier.wait" title="threading.Barrier.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a> method.</p>
<dl class="method">
<dt id="threading.Barrier.wait">
<tt class="descname">wait</tt><big>(</big><em>timeout=None</em><big>)</big><a class="headerlink" href="#threading.Barrier.wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Pass the barrier.  When all the threads party to the barrier have called
this function, they are all released simultaneously.  If a <em>timeout</em> is
provided, it is used in preference to any that was supplied to the class
constructor.</p>
<p>The return value is an integer in the range 0 to <em>parties</em> &#8211; 1, different
for each thread.  This can be used to select a thread to do some special
housekeeping, e.g.:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">i</span> <span class="o">=</span> <span class="n">barrier</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
<span class="k">if</span> <span class="n">i</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
    <span class="c"># Only one thread needs to print this</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;passed the barrier&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If an <em>action</em> was provided to the constructor, one of the threads will
have called it prior to being released.  Should this call raise an error,
the barrier is put into the broken state.</p>
<p>If the call times out, the barrier is put into the broken state.</p>
<p>This method may raise a <a class="reference internal" href="#threading.BrokenBarrierError" title="threading.BrokenBarrierError"><tt class="xref py py-class docutils literal"><span class="pre">BrokenBarrierError</span></tt></a> exception if the
barrier is broken or reset while a thread is waiting.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Barrier.reset">
<tt class="descname">reset</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Barrier.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the barrier to the default, empty state.  Any threads waiting on it
will receive the <a class="reference internal" href="#threading.BrokenBarrierError" title="threading.BrokenBarrierError"><tt class="xref py py-class docutils literal"><span class="pre">BrokenBarrierError</span></tt></a> exception.</p>
<p>Note that using this function may can require some external
synchronization if there are other threads whose state is unknown.  If a
barrier is broken it may be better to just leave it and create a new one.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Barrier.abort">
<tt class="descname">abort</tt><big>(</big><big>)</big><a class="headerlink" href="#threading.Barrier.abort" title="Permalink to this definition">¶</a></dt>
<dd><p>Put the barrier into a broken state.  This causes any active or future
calls to <a class="reference internal" href="#threading.Barrier.wait" title="threading.Barrier.wait"><tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt></a> to fail with the <a class="reference internal" href="#threading.BrokenBarrierError" title="threading.BrokenBarrierError"><tt class="xref py py-class docutils literal"><span class="pre">BrokenBarrierError</span></tt></a>.  Use
this for example if one of the needs to abort, to avoid deadlocking the
application.</p>
<p>It may be preferable to simply create the barrier with a sensible
<em>timeout</em> value to automatically guard against one of the threads going
awry.</p>
</dd></dl>

<dl class="attribute">
<dt id="threading.Barrier.parties">
<tt class="descname">parties</tt><a class="headerlink" href="#threading.Barrier.parties" title="Permalink to this definition">¶</a></dt>
<dd><p>The number of threads required to pass the barrier.</p>
</dd></dl>

<dl class="attribute">
<dt id="threading.Barrier.n_waiting">
<tt class="descname">n_waiting</tt><a class="headerlink" href="#threading.Barrier.n_waiting" title="Permalink to this definition">¶</a></dt>
<dd><p>The number of threads currently waiting in the barrier.</p>
</dd></dl>

<dl class="attribute">
<dt id="threading.Barrier.broken">
<tt class="descname">broken</tt><a class="headerlink" href="#threading.Barrier.broken" title="Permalink to this definition">¶</a></dt>
<dd><p>A boolean that is <tt class="docutils literal"><span class="pre">True</span></tt> if the barrier is in the broken state.</p>
</dd></dl>

</dd></dl>

<dl class="exception">
<dt id="threading.BrokenBarrierError">
<em class="property">exception </em><tt class="descclassname">threading.</tt><tt class="descname">BrokenBarrierError</tt><a class="headerlink" href="#threading.BrokenBarrierError" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception, a subclass of <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a>, is raised when the
<a class="reference internal" href="#threading.Barrier" title="threading.Barrier"><tt class="xref py py-class docutils literal"><span class="pre">Barrier</span></tt></a> object is reset or broken.</p>
</dd></dl>

</div>
<div class="section" id="using-locks-conditions-and-semaphores-in-the-with-statement">
<span id="with-locks"></span><h2>17.1.10. Using locks, conditions, and semaphores in the <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement<a class="headerlink" href="#using-locks-conditions-and-semaphores-in-the-with-statement" title="Permalink to this headline">¶</a></h2>
<p>All of the objects provided by this module that have <tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt> and
<tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt> methods can be used as context managers for a <a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>
statement.  The <tt class="xref py py-meth docutils literal"><span class="pre">acquire()</span></tt> method will be called when the block is
entered, and <tt class="xref py py-meth docutils literal"><span class="pre">release()</span></tt> will be called when the block is exited.  Hence,
the following snippet:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">with</span> <span class="n">some_lock</span><span class="p">:</span>
    <span class="c"># do something...</span>
</pre></div>
</div>
<p>is equivalent to:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">some_lock</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
    <span class="c"># do something...</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">some_lock</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>
</pre></div>
</div>
<p>Currently, <a class="reference internal" href="#threading.Lock" title="threading.Lock"><tt class="xref py py-class docutils literal"><span class="pre">Lock</span></tt></a>, <a class="reference internal" href="#threading.RLock" title="threading.RLock"><tt class="xref py py-class docutils literal"><span class="pre">RLock</span></tt></a>, <a class="reference internal" href="#threading.Condition" title="threading.Condition"><tt class="xref py py-class docutils literal"><span class="pre">Condition</span></tt></a>,
<a class="reference internal" href="#threading.Semaphore" title="threading.Semaphore"><tt class="xref py py-class docutils literal"><span class="pre">Semaphore</span></tt></a>, and <a class="reference internal" href="#threading.BoundedSemaphore" title="threading.BoundedSemaphore"><tt class="xref py py-class docutils literal"><span class="pre">BoundedSemaphore</span></tt></a> objects may be used as
<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement context managers.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">17.1. <tt class="docutils literal"><span class="pre">threading</span></tt> &#8212; Thread-based parallelism</a><ul>
<li><a class="reference internal" href="#thread-local-data">17.1.1. Thread-Local Data</a></li>
<li><a class="reference internal" href="#thread-objects">17.1.2. Thread Objects</a></li>
<li><a class="reference internal" href="#lock-objects">17.1.3. Lock Objects</a></li>
<li><a class="reference internal" href="#rlock-objects">17.1.4. RLock Objects</a></li>
<li><a class="reference internal" href="#condition-objects">17.1.5. Condition Objects</a></li>
<li><a class="reference internal" href="#semaphore-objects">17.1.6. Semaphore Objects</a><ul>
<li><a class="reference internal" href="#semaphore-example">17.1.6.1. <tt class="docutils literal"><span class="pre">Semaphore</span></tt> Example</a></li>
</ul>
</li>
<li><a class="reference internal" href="#event-objects">17.1.7. Event Objects</a></li>
<li><a class="reference internal" href="#timer-objects">17.1.8. Timer Objects</a></li>
<li><a class="reference internal" href="#barrier-objects">17.1.9. Barrier Objects</a></li>
<li><a class="reference internal" href="#using-locks-conditions-and-semaphores-in-the-with-statement">17.1.10. Using locks, conditions, and semaphores in the <tt class="docutils literal"><span class="pre">with</span></tt> statement</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="concurrency.html"
                        title="previous chapter">17. Concurrent Execution</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="multiprocessing.html"
                        title="next chapter">17.2. <tt class="docutils literal"><span class="pre">multiprocessing</span></tt> &#8212; Process-based parallelism</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/library/threading.txt"
         rel="nofollow">Show Source</a></li>
</ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="multiprocessing.html" title="17.2. multiprocessing — Process-based parallelism"
             >next</a> |</li>
        <li class="right" >
          <a href="concurrency.html" title="17. Concurrent Execution"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &raquo;</li>
        <li>
          <span class="version_switcher_placeholder">3.4.3</span>
          <a href="../index.html">Documentation</a> &raquo;
        </li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="concurrency.html" >17. Concurrent Execution</a> &raquo;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2015, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Aug 31, 2015.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.3.
    </div>

  </body>
</html>